<template>
  <div>
    <span v-if="props.showText">{{currName}}</span>
    <el-radio-group
      v-else
      v-model="modelValue"
      @change="handleChange"
    >
      <el-radio
        v-for="item in options"
        :key="item.key"
        :value="item.key"
      >{{item.value}}</el-radio>
    </el-radio-group>
  </div>
</template>

<script setup>
import { ref, watch } from 'vue';
import { getDictionary } from '@/utils/system';

const emit = defineEmits(['change']);
const props = defineProps({
  dictCode: String,
  showText: Boolean
});

const modelValue = defineModel();
const currName = ref('');
const options = ref([]);

const handleChange = () => {
  emit('change');
};

const loadDicAndShow = async(dictCode) => {
  if ((dictCode || '') === '') {
    options.value = [];
  } else {
    options.value = await getDictionary(dictCode);
  }

  calcValue();
};

const calcValue = () => {
  currName.value = '';
  if (props.showText) {
    options.value.forEach(option => {
      if (option.key === modelValue.value) {
        currName.value = option.value;
      }
    });
  }
};

const init = (dictCode) => {
  loadDicAndShow(dictCode);
};

watch(() => props.dictCode, (dictCode) => {
  init(dictCode);
}, {immediate: true});

watch(() => modelValue.value, () => {
  calcValue();
});
</script>